package com.xiaoyun.interceptor;

import com.xiaoyun.constant.Const;
import com.xiaoyun.utils.JsonUtils;
import com.xiaoyun.utils.RedisUtil;
import com.xiaoyun.utils.XYJSONResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)) {
            String uniqueToken = redisUtil.getKey(Const.REDIS_USER_TOKEN + ":" + userId);
            if (StringUtils.isBlank(uniqueToken)) {
                returnErrorResponse(response, XYJSONResult.errorMap("请登录.."));
                return false;
            } else {
                if (!uniqueToken.equals(userToken)) {
                    returnErrorResponse(response, XYJSONResult.errorMap("账号可能异地登录.."));
                    return false;
                }
            }
        } else {
            returnErrorResponse(response, XYJSONResult.errorMap("请登录.."));
            return false;
        }

        return true;
    }

    public void returnErrorResponse(HttpServletResponse response, XYJSONResult result) {

        try (OutputStream out = response.getOutputStream()) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
